package com.lfy.modules.blog.aop;

import com.lfy.modules.blog.cache.AuthCache;
import com.lfy.modules.blog.domain.AuthorityEntity;
import com.lfy.modules.blog.domain.RoleAuthorityContactEntity;
import com.lfy.modules.blog.service.AuthorityService;
import com.lfy.modules.blog.service.RoleAuthorityContactService;
import com.lfy.modules.common.anno.Authentication;
import com.lfy.modules.common.anno.NoNeedLogin;
import com.lfy.modules.common.domain.BaseEnum;
import com.lfy.modules.common.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
/**
 *  权限校验
 *
 * @author <a href="https://www.lvfeiy.top">lvfeiyang</a>
 * @date 2024/4/25 1:02
 */
@Aspect
@Component
@Slf4j
public class AuthAspect implements InitializingBean {


    @Pointcut(value = "@annotation(authentication)")
    public void authPointcut(Authentication authentication) {

    }
    @Around(value = "authPointcut(authentication)", argNames = "joinPoint,authentication")
    public Object around(ProceedingJoinPoint joinPoint, Authentication authentication) throws Throwable {

            log.info("权限校验逻辑");
            log.info(authentication.value());
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        NoNeedLogin noNeedLogin = AnnotationUtils.getAnnotation(signature.getMethod(), NoNeedLogin.class);
        if(Objects.nonNull(noNeedLogin)){
            return joinPoint.proceed();
        }
        String key = authentication.value();
        boolean haveAuth = AuthCache.isHaveAuth(key);
        if(haveAuth){
            return joinPoint.proceed();
        }
        return R.error(BaseEnum.authEnum.NO_AUTH);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("权限校验初始化");
        AuthCache.init();
    }
}
